<template>
  <div class="equipment-3d-visualization">
    <el-tabs v-model="activeTab">
      <!-- 指标配置页 -->
      <el-tab-pane label="指标配置" name="config">
        <div class="config-section">
          <el-form :model="configForm" label-width="120px" class="config-form">
            <el-form-item label="统计项">
              <el-checkbox-group v-model="configForm.metrics">
                <el-checkbox label="非计划停机时间减少率"></el-checkbox>
                <el-checkbox label="维护成本下降率"></el-checkbox>
                <el-checkbox label="OEE"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="统计周期">
              <el-radio-group v-model="configForm.period">
                <el-radio label="日"></el-radio>
                <el-radio label="周"></el-radio>
                <el-radio label="月"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="维度">
              <el-radio-group v-model="configForm.dimension">
                <el-radio label="车间"></el-radio>
                <el-radio label="设备类型"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveConfig">保存配置</el-button>
              <el-button @click="resetConfig">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 分析看板页 -->
      <el-tab-pane label="分析看板" name="dashboard">
        <div class="dashboard-section">
          <div class="dashboard-controls">
            <el-select v-model="chartType" placeholder="选择图表类型" style="width: 180px;">
              <el-option label="OEE对比（柱状图）" value="bar"></el-option>
              <el-option label="维护成本趋势（折线图）" value="line"></el-option>
              <el-option label="故障类型占比（饼图）" value="pie"></el-option>
            </el-select>
            <el-button v-if="canDrillDown" @click="drillDown" type="primary" size="mini" style="margin-left: 10px;">
              下钻查看设备
            </el-button>
            <el-button v-if="isDrilled" @click="backToWorkshop" size="mini" style="margin-left: 10px;">
              返回车间
            </el-button>
          </div>
          <div ref="chart" class="dashboard-chart"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import echarts from 'echarts'
const CONFIG_KEY = 'equipment_dashboard_config'

export default {
  name: 'Equipment3DVisualization',
  data() {
    return {
      activeTab: 'config',
      // 指标配置表单
      configForm: {
        metrics: [],
        period: '月',
        dimension: '车间'
      },
      // 图表类型
      chartType: 'bar',
      // 是否已下钻
      isDrilled: false,
      // 当前下钻的车间
      drilledWorkshop: '',
      // mock 数据
      workshops: [
        { name: '装配车间', OEE: 85, costTrend: [120, 110, 105, 100, 98, 102], devices: [
          { name: '装配设备A', OEE: 88, costTrend: [60, 55, 53, 50, 49, 51], faults: { '电气故障': 2, '机械故障': 1 } },
          { name: '装配设备B', OEE: 82, costTrend: [60, 55, 52, 50, 49, 51], faults: { '电气故障': 1, '液压故障': 2 } }
        ], faults: { '电气故障': 3, '机械故障': 1, '液压故障': 2 } },
        { name: '机加工车间', OEE: 78, costTrend: [130, 128, 120, 115, 110, 111], devices: [
          { name: '机加设备A', OEE: 80, costTrend: [70, 68, 65, 60, 58, 59], faults: { '机械故障': 2, '液压故障': 1 } },
          { name: '机加设备B', OEE: 76, costTrend: [60, 60, 55, 55, 52, 52], faults: { '电气故障': 1, '机械故障': 1 } }
        ], faults: { '电气故障': 1, '机械故障': 3, '液压故障': 1 } }
      ],
      // 故障类型
      faultTypes: ['电气故障', '机械故障', '液压故障']
    }
  },
  computed: {
    canDrillDown() {
      return this.chartType === 'bar' && !this.isDrilled
    }
  },
  mounted() {
    this.loadConfig()
    this.$nextTick(this.renderChart)
  },
  watch: {
    chartType() {
      this.isDrilled = false
      this.$nextTick(this.renderChart)
    },
    isDrilled() {
      this.$nextTick(this.renderChart)
    }
  },
  methods: {
    // 保存配置到本地
    saveConfig() {
      localStorage.setItem(CONFIG_KEY, JSON.stringify(this.configForm))
      this.$message.success('配置已保存')
    },
    // 重置配置
    resetConfig() {
      this.configForm = {
        metrics: [],
        period: '月',
        dimension: '车间'
      }
      localStorage.removeItem(CONFIG_KEY)
    },
    // 加载配置
    loadConfig() {
      const config = localStorage.getItem(CONFIG_KEY)
      if (config) {
        this.configForm = JSON.parse(config)
      }
    },
    // 渲染图表
    renderChart() {
      if (!this.$refs.chart) return
      const chart = echarts.init(this.$refs.chart)
      let option = {}
      if (this.chartType === 'bar') {
        // 柱状图：OEE对比
        if (!this.isDrilled) {
          option = {
            title: { text: '各车间OEE对比', left: 'center', textStyle: { color: '#fff' } },
            tooltip: {},
            xAxis: { data: this.workshops.map(w => w.name), axisLabel: { color: '#fff' } },
            yAxis: { axisLabel: { color: '#fff' } },
            series: [{
              name: 'OEE',
              type: 'bar',
              data: this.workshops.map(w => w.OEE),
              itemStyle: { color: '#3398DB' }
            }]
          }
        } else {
          // 下钻到设备
          const ws = this.workshops.find(w => w.name === this.drilledWorkshop)
          option = {
            title: { text: `${ws.name}设备OEE对比`, left: 'center', textStyle: { color: '#fff' } },
            tooltip: {},
            xAxis: { data: ws.devices.map(d => d.name), axisLabel: { color: '#fff' } },
            yAxis: { axisLabel: { color: '#fff' } },
            series: [{
              name: 'OEE',
              type: 'bar',
              data: ws.devices.map(d => d.OEE),
              itemStyle: { color: '#91cc75' }
            }]
          }
        }
      } else if (this.chartType === 'line') {
        // 折线图：维护成本趋势
        if (!this.isDrilled) {
          option = {
            title: { text: '各车间维护成本趋势', left: 'center', textStyle: { color: '#fff' } },
            tooltip: { trigger: 'axis' },
            legend: { data: this.workshops.map(w => w.name), textStyle: { color: '#fff' } },
            xAxis: { type: 'category', data: ['6月前', '5月前', '4月前', '3月前', '2月前', '1月前'], axisLabel: { color: '#fff' } },
            yAxis: { axisLabel: { color: '#fff' } },
            series: this.workshops.map(w => ({
              name: w.name,
              type: 'line',
              data: w.costTrend
            }))
          }
        } else {
          // 下钻到设备
          const ws = this.workshops.find(w => w.name === this.drilledWorkshop)
          option = {
            title: { text: `${ws.name}设备维护成本趋势`, left: 'center', textStyle: { color: '#fff' } },
            tooltip: { trigger: 'axis' },
            legend: { data: ws.devices.map(d => d.name), textStyle: { color: '#fff' } },
            xAxis: { type: 'category', data: ['6月前', '5月前', '4月前', '3月前', '2月前', '1月前'], axisLabel: { color: '#fff' } },
            yAxis: { axisLabel: { color: '#fff' } },
            series: ws.devices.map(d => ({
              name: d.name,
              type: 'line',
              data: d.costTrend
            }))
          }
        }
      } else if (this.chartType === 'pie') {
        // 饼图：故障类型占比
        let data = []
        let title = '各车间故障类型占比'
        if (!this.isDrilled) {
          // 汇总所有车间
          const total = {}
          this.faultTypes.forEach(type => { total[type] = 0 })
          this.workshops.forEach(w => {
            this.faultTypes.forEach(type => {
              total[type] += w.faults[type] || 0
            })
          })
          data = this.faultTypes.map(type => ({ name: type, value: total[type] }))
        } else {
          // 下钻到设备
          const ws = this.workshops.find(w => w.name === this.drilledWorkshop)
          const total = {}
          this.faultTypes.forEach(type => { total[type] = 0 })
          ws.devices.forEach(d => {
            this.faultTypes.forEach(type => {
              total[type] += d.faults[type] || 0
            })
          })
          data = this.faultTypes.map(type => ({ name: type, value: total[type] }))
          title = `${ws.name}设备故障类型占比`
        }
        option = {
          title: { text: title, left: 'center', textStyle: { color: '#fff' } },
          tooltip: { trigger: 'item' },
          legend: { bottom: 10, left: 'center', textStyle: { color: '#fff' } },
          series: [{
            name: '故障类型',
            type: 'pie',
            radius: '50%',
            data,
            label: { color: '#fff' }
          }]
        }
      }
      chart.setOption(option)
      window.addEventListener('resize', chart.resize)
      this.chartInstance = chart
    },
    // 下钻
    drillDown() {
      // 默认下钻第一个车间
      this.drilledWorkshop = this.workshops[0].name
      this.isDrilled = true
    },
    // 返回车间
    backToWorkshop() {
      this.isDrilled = false
      this.drilledWorkshop = ''
    }
  }
}
</script>

<style scoped>
.equipment-3d-visualization {
  background: #101c2c;
  min-height: 100vh;
  padding: 24px;
}
.config-section {
  max-width: 600px;
  margin: 40px auto;
  background: rgba(20,40,80,0.9);
  border-radius: 8px;
  padding: 32px 24px;
  box-shadow: 0 2px 12px #0006;
}
.config-form .el-form-item__label {
  color: #fff;
}
.dashboard-section {
  margin: 0 auto;
  max-width: 900px;
  background: rgba(20,40,80,0.9);
  border-radius: 8px;
  padding: 32px 24px;
  box-shadow: 0 2px 12px #0006;
}
.dashboard-controls {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}
.dashboard-chart {
  width: 100%;
  height: 420px;
  background: #0a1422;
  border-radius: 8px;
}
</style>
